﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using Hxsoft.AppV1.Module;

namespace Hxsoft.AppV1.WebUI
{
	public class LinkClassSpecialModule : ISpecialModuleParser
	{
		public string BuildListUrl(string specialCode, string pageCode, string moduleCode, int? pageIndex)
		{
			return GenericUrlManager.BuildSpecialModuleListUrl(specialCode, pageCode, moduleCode, pageIndex);
		}

		public string BuildContentUrl(string specialCode, string pageCode, string moduleCode, int infoId)
		{
			return GenericUrlManager.BuildSpecialModuleContentUrl(specialCode, pageCode, moduleCode, infoId.ToString());
		}

		public string ParsePart(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, SpecialPageConfiguration configuration, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page, bool isPreview)
		{
			string content = "";
			if (configuration == null) return content;
			if (module == null || module.ModuleId != configuration.ModuleId) return content;

			SpecialLinkPageConfiguration con = configuration as SpecialLinkPageConfiguration;
			if (con == null) con = new SpecialLinkPageConfiguration();
			if (string.IsNullOrEmpty(con.ListTarget)) con.ListTarget = "_blank";
			if (string.IsNullOrEmpty(con.ItemTarget)) con.ItemTarget = "_blank";
			SpecialContentTemplate contentTemplate = templateConfiguration.GetBlockTemplate(module.ModuleType, con.ListType);
			if (contentTemplate == null) return content;

			SpecialLinkContentConfiguration moduleCon = module.ContentConfigurationObject as SpecialLinkContentConfiguration;
			string contentPageCode = moduleCon == null ? "" : moduleCon.ContentPage;

			content = contentTemplate.GetTemplate(con.Parameters);
			Regex reg = new Regex(@"<headerTemplate>((?:.|\n|\r)*?)</headerTemplate>", RegexOptions.IgnoreCase);
			if (con.ShowHeader == false)
				content = reg.Replace(content, "");
			else
				content = reg.Replace(content, "$1");

			Regex regMore = new Regex(@"<moreTemplate>((?:.|\n|\r)*?)</moreTemplate>", RegexOptions.IgnoreCase);
			bool showMore = con.ShowMore.HasValue ? con.ShowMore.Value : con.LoadCount.HasValue;
			if (showMore == false)
				content = regMore.Replace(content, "");
			else
				content = regMore.Replace(content, "$1");

			content = content.Replace("{ListTitle}", module.ModuleName);
			content = content.Replace("{ListUrl}", BuildListUrl(specialInfo.SpecialCode, contentPageCode, module.ModuleCode, null));
			content = content.Replace("{ListTarget}", con.ListTarget);
			content = content.Replace("{ListTargetAttribute}", string.IsNullOrEmpty(con.ListTarget) ? "" : @" target=""" + con.ListTarget + @"""");
			content = content.Replace("{CssClass}", string.IsNullOrEmpty(con.CssClass) ? "" : @" class=""" + con.CssClass + @"""");
			content = content.Replace("{AttachedClass}", string.IsNullOrEmpty(con.CssClass) ? "" : @" " + con.CssClass);
			content = content.Replace("{ImageWidthStyle}", con.ImageWidth.HasValue ? "width:" + con.ImageWidth.ToString() + "px;" : "");
			content = content.Replace("{ImageHeightStyle}", con.ImageHeight.HasValue ? "height:" + con.ImageHeight.ToString() + "px;" : "");
			content = content.Replace("{ModuleIndex}", page.ModuleCounter.ToString());

			List<Links.LinkForImageList> list = null;

			if (isPreview)	// 读预览数据。
			{
				string json = templateConfiguration.GetBlockPreviewData(module.ModuleType, contentTemplate.ViewType);
				if (!string.IsNullOrEmpty(json)) list = Serialization.DeserializeJson<List<Links.LinkForImageList>>(json);
			}

			if (list == null) list = Links.GetImageList(int.Parse(module.RefModuleId), con.LoadCount);

			// 默认图片Url。
			string defaultImageUrl = string.IsNullOrEmpty(contentTemplate.DefaultImageUrl) ? templateConfiguration.DefaultImageUrl : contentTemplate.DefaultImageUrl;
			if (!string.IsNullOrEmpty(defaultImageUrl))
			{
				defaultImageUrl = defaultImageUrl.Replace(SpecialPages.TemplateConst_TemplateRootUrl, SpecialPages.TemplateRootUrl);
				defaultImageUrl = defaultImageUrl.Replace(SpecialPages.TemplateConst_TemplateFolder, pageInfo.TemplateRootUrl);
			}

			Regex reg2 = new Regex("<itemTemplate>((?:.|\n|\r)*?)</itemTemplate>", RegexOptions.IgnoreCase);
			Match match2 = reg2.Match(content);
			if (match2 != Match.Empty)
			{
				string items = "";
				string itemTemplate = match2.Groups[1].Value;
				string imageStyle = "";
				if (con.ImageWidth.HasValue || con.ImageHeight.HasValue) imageStyle = @" style=""" + (con.ImageWidth.HasValue ? "width:" + con.ImageWidth + "px;" : "") + (con.ImageHeight.HasValue ? "height:" + con.ImageHeight + "px;" : "") + @"""";
				foreach (var data in list)
				{
					string item = itemTemplate.Replace("{ItemUrl}", data.LinkUrl);
					item = item.Replace("{ItemTarget}", con.ItemTarget);
					item = item.Replace("{ItemTargetAttribute}", string.IsNullOrEmpty(con.ItemTarget) ? "" : @" target=""" + con.ItemTarget + @"""");
					item = item.Replace("{ItemImage}", string.IsNullOrEmpty(data.ImageType) && string.IsNullOrEmpty(defaultImageUrl) ? "" : string.Format(@"<img src=""{0}"" alt=""{1}""{2} />", GenericUrlManager.GetInfoResourceThumbnailGeneratorUrl(data.ImageType, null, null, defaultImageUrl), data.Title, imageStyle));
					item = item.Replace("{ItemSourceTitle}", data.Title);
					item = item.Replace("{ItemEncodeSourceTitle}", HttpUtility.HtmlEncode(data.Title));
					item = item.Replace("{ItemImageUrl}", GenericUrlManager.GetInfoResourceThumbnailGeneratorUrl(data.ImageType, null));
					item = item.Replace("{ItemTitle}", StringExtensions.CutString(data.Title, con.TitleCapacity, "..."));

					items += item;
				}

				content = reg2.Replace(content, items);
			}

			if (contentTemplate.HeadIncludeFiles != null)	// 头部包含文件
			{
				foreach(var file in contentTemplate.HeadIncludeFiles)
					page.RegisterHeadIncludeFile(file.Key, file.Value);
			}

			if (isPreview)		// 加载预览样式
			{
				page.TemplateCssUrls = templateConfiguration.TemplateCssUrls;
				if (page.TemplateCssUrls != null)
				{
					for (int i = 0; i < page.TemplateCssUrls.Length; i++)
					{
						var url = page.TemplateCssUrls[i];
						if (!string.IsNullOrEmpty(url))
							page.TemplateCssUrls[i] = url.Replace(SpecialPages.TemplateConst_TemplateRootUrl, SpecialPages.TemplateRootUrl);
					}
				}
			}

			// 替换其它模板变量
			content = GenericHelper.ReplaceSpecialTemplateParameters(content, contentTemplate.OtherParameters, con.Parameters);

			return content;
		}

		public string ParseContent(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page, bool isPreview)
		{
			string content = "";
			if (module == null) return content;

			if (isPreview) return content;		// 没有预览内容。

			HttpContext context = HttpContext.Current;

			int infoId = int.Parse(context.Request.QueryString[GenericUrlManager.Special_Query_ModuleInfoIdField]);

			SpecialLinkContentConfiguration con = module.ContentConfigurationObject as SpecialLinkContentConfiguration;
			if (con == null) con = new SpecialLinkContentConfiguration();
			if (string.IsNullOrEmpty(con.ListItemTarget)) con.ListItemTarget = "_blank";
			string contentPageCode = con.ContentPage;

			// 当前位置
			page.Locations.Add(new NavigationItem() { Text = module.ModuleName, Url = BuildListUrl(specialInfo.SpecialCode, contentPageCode, module.ModuleCode, null) });
			page.Locations.Add(new NavigationItem() { Text = Res.Content, Url = BuildContentUrl(specialInfo.SpecialCode, contentPageCode, module.ModuleCode, infoId) });

			return "";
		}

		public string ParseList(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page, bool isPreview)
		{
			string content = "";
			if (module == null) return content;

			SpecialLinkContentConfiguration con = module.ContentConfigurationObject as SpecialLinkContentConfiguration;
			if (con == null) con = new SpecialLinkContentConfiguration();
			if (string.IsNullOrEmpty(con.ListItemTarget)) con.ListItemTarget = "_blank";
			SpecialContentTemplate contentTemplate = templateConfiguration.GetContentTemplate(module.ModuleType, SpecialLinkContentViewType.List.ToString(), con.ListType);
			if (contentTemplate == null) return content;

			string contentPageCode = con.ContentPage;
			int currentPage = 1;
			PaginationInfo<List<Links.LinkForImageList>> paginationInfo = null;

			if (isPreview)	// 读预览数据。
			{
				string json = templateConfiguration.GetContentPreviewData(module.ModuleType, SpecialLinkContentViewType.List.ToString(), contentTemplate.ViewType);
				if (!string.IsNullOrEmpty(json)) paginationInfo = Serialization.DeserializeJson<PaginationInfo<List<Links.LinkForImageList>>>(json);
			}
			else
			{
				HttpContext context = HttpContext.Current;
				currentPage = IntExtensions.ParseOrDefault(context.Request.QueryString[GenericUrlManager.Special_Query_ModulePageField], 1);
			}

			if (paginationInfo == null) paginationInfo = Links.GetPaginationImageList(int.Parse(module.RefModuleId), con.ListPageSize.GetValueOrDefault(20), currentPage);
			if (paginationInfo == null) return content;

			content = contentTemplate.GetTemplate(con.ListParameters);
			Regex reg = new Regex("<headerTemplate>((?:.|\n|\r)*?)</headerTemplate>", RegexOptions.IgnoreCase);
			content = reg.Replace(content, "$1");
			content = content.Replace("{ListTitle}", module.ModuleName);
			content = content.Replace("{CssClass}", string.IsNullOrEmpty(con.ListCssClass) ? "" : @" class=""" + con.ListCssClass + @"""");
			content = content.Replace("{AttachedClass}", string.IsNullOrEmpty(con.ListCssClass) ? "" : @" " + con.ListCssClass);
			content = content.Replace("{ImageWidthStyle}", con.ListImageWidth.HasValue ? "width:" + con.ListImageWidth.ToString() + "px;" : "");
			content = content.Replace("{ImageHeightStyle}", con.ListImageHeight.HasValue ? "height:" + con.ListImageHeight.ToString() + "px;" : "");
			content = content.Replace("{ModuleIndex}", page.ModuleCounter.ToString());

			// 默认图片Url。
			string defaultImageUrl = string.IsNullOrEmpty(contentTemplate.DefaultImageUrl) ? templateConfiguration.DefaultImageUrl : contentTemplate.DefaultImageUrl;
			if (!string.IsNullOrEmpty(defaultImageUrl))
			{
				defaultImageUrl = defaultImageUrl.Replace(SpecialPages.TemplateConst_TemplateRootUrl, SpecialPages.TemplateRootUrl);
				defaultImageUrl = defaultImageUrl.Replace(SpecialPages.TemplateConst_TemplateFolder, pageInfo.TemplateRootUrl);
			}

			Regex reg2 = new Regex("<itemTemplate>((?:.|\n|\r)*?)</itemTemplate>", RegexOptions.IgnoreCase);
			Match match2 = reg2.Match(content);
			if (match2 != Match.Empty)
			{
				string items = "";
				string itemTemplate = match2.Groups[1].Value;
				string imageStyle = "";
				if (con.ListImageWidth.HasValue || con.ListImageHeight.HasValue) imageStyle = @" style=""" + (con.ListImageWidth.HasValue ? "width:" + con.ListImageWidth + "px;" : "") + (con.ListImageHeight.HasValue ? "height:" + con.ListImageHeight + "px;" : "") + @"""";
				foreach (var data in paginationInfo.Records)
				{
					string item = itemTemplate.Replace("{ItemUrl}", data.LinkUrl);
					item = item.Replace("{ItemTarget}", con.ListItemTarget);
					item = item.Replace("{ItemTargetAttribute}", string.IsNullOrEmpty(con.ListItemTarget) ? "" : @" target=""" + con.ListItemTarget + @"""");
					item = item.Replace("{ItemImage}", string.IsNullOrEmpty(data.ImageType) && string.IsNullOrEmpty(defaultImageUrl) ? "" : string.Format(@"<img src=""{0}"" alt=""{1}""{2} />", GenericUrlManager.GetInfoResourceThumbnailGeneratorUrl(data.ImageType, null, null, defaultImageUrl), data.Title, imageStyle));
					item = item.Replace("{ItemSourceTitle}", data.Title);
					item = item.Replace("{ItemEncodeSourceTitle}", HttpUtility.HtmlEncode(data.Title));
					item = item.Replace("{ItemImageUrl}", GenericUrlManager.GetInfoResourceThumbnailGeneratorUrl(data.ImageType, null));
					item = item.Replace("{ItemTitle}", StringExtensions.CutString(data.Title, con.ListTitleCapacity, "..."));

					items += item;
				}

				content = reg2.Replace(content, items);
			}

			content = content.Replace("{Pager}", GenericHelper.BuildSpecialListPager(paginationInfo, GenericUrlManager.BuildSpecialModuleListUrlPattern(specialInfo.SpecialCode, contentPageCode, module.ModuleCode)));

			if (contentTemplate.HeadIncludeFiles != null)	// 头部包含文件
			{
				foreach (var file in contentTemplate.HeadIncludeFiles)
					page.RegisterHeadIncludeFile(file.Key, file.Value);
			}

			if (isPreview)		// 加载预览样式
			{
				page.TemplateCssUrls = templateConfiguration.TemplateCssUrls;
				if (page.TemplateCssUrls != null)
				{
					for (int i = 0; i < page.TemplateCssUrls.Length; i++)
					{
						var url = page.TemplateCssUrls[i];
						if (!string.IsNullOrEmpty(url))
							page.TemplateCssUrls[i] = url.Replace(SpecialPages.TemplateConst_TemplateRootUrl, SpecialPages.TemplateRootUrl);
					}
				}
			}

			// 替换其它模板变量
			content = GenericHelper.ReplaceSpecialTemplateParameters(content, contentTemplate.OtherParameters, con.ListParameters);

			// 当前位置
			page.Locations.Add(new NavigationItem() { Text = module.ModuleName, Url = BuildListUrl(specialInfo.SpecialCode, contentPageCode, module.ModuleCode, null) });
			page.Title += "_" + module.ModuleName + Page.TitleSectionSeparator + string.Format(Res.TitlePaging, currentPage) + Hxsoft.AppV1.Page.TitleSuffix;	// 更新页面标题
			page.MetaKeywords += (string.IsNullOrEmpty(page.MetaKeywords) ? "" : ",") + module.ModuleName;

			return content;
		}

		#region ISpecialModuleParser 成员

		string ISpecialModuleParser.ParsePreviewPart(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, SpecialPageConfiguration configuration, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page)
		{
			return ParsePart(templateConfiguration, module, configuration, specialInfo, pageInfo, ref page, true);
		}

		string ISpecialModuleParser.ParsePreviewContent(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page, string moduleView)
		{
			if (moduleView == "Content")
				return ParseContent(templateConfiguration, module, specialInfo, pageInfo, ref page, true);
			else
				return ParseList(templateConfiguration, module, specialInfo, pageInfo, ref page, true);
		}


		string ISpecialModuleParser.ParsePart(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, SpecialPageConfiguration configuration, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page)
		{
			return ParsePart(templateConfiguration, module, configuration, specialInfo, pageInfo, ref page, false);
		}

		string ISpecialModuleParser.ParseContent(SpecialTemplateConfiguration templateConfiguration, SpecialModule module, Special specialInfo, SpecialPage pageInfo, ref SpecialPageInfo page)
		{
			HttpContext context = HttpContext.Current;
			string view = context.Request.QueryString[GenericUrlManager.Special_Query_ModuleViewField];
			if (view == "Content")
				return ParseContent(templateConfiguration, module, specialInfo, pageInfo, ref page, false);
			else
				return ParseList(templateConfiguration, module, specialInfo, pageInfo, ref page, false);
		}

		#endregion
	}
}
